class ApplicationController < ActionController::Base
  helper :all
  helper_method :errors;

  # See ActionController::RequestForgeryProtection for details
  # Uncomment the :secret if you're not using the cookie session store
  protect_from_forgery # :secret => '6b033ed5f0b0139f8956ed8284eb4ffa'
  
  # See ActionController::Base for details 
  # Uncomment this to filter the contents of submitted sensitive data parameters
  # from your application log (in this case, all fields with names like "password"). 
  # filter_parameter_logging :password

  session :on
  session :session_key => 'sicorp_session'

  helper :html_content, :paginacao, :opcoes_controle, :autenticacao

  def index
    unless session[:usuario]
      redirect_to :controller => '/autenticacao', :action => :logon
    end
  end

  def cancel
    redirect_to redirecionamento_padrao
  end

protected

  def errors(obj, opts={})
    opts = {:class => "", :message => ""}.merge(opts);
    klass = " class=#{opts[:class]}" if opts[:class] != "";
    msg = "#{obj.errors.length} Erros Prováveis. " + opts[:message] + "<br />" if opts[:message] != "";
    tag = "#{msg}\n<ul#{klass}>\n";
    attrs = obj.class::AttributesNames || {};
    attrs = Hash.new{|hash, key| hash[key] = key.to_s;}.merge(attrs);
    obj.errors.each do |attr, msg|
      tag << "<li>'#{attrs[attr.to_sym]}' #{msg}</li>\n";
    end
    tag + "</ul>";
  end

  def usuario
    @usuario = session[:usuario]
  end

  def usuario_nao_autorizado
    flash[:warning] = "Usuário não possui privilégios."
    redirect_to url_for(:controller => '')
  end

  def redirecionamento_padrao
    { :controller => '', :action => :resumo, :tipo => :geral }
  end

private

  def autenticar_usuario
    unless session[:usuario]
      session[:uri] = url_for(params)
      flash[:warning] = "Não necessário estar autenticado."
      redirect_to(url_for(:controller => '/autenticacao', :action => :logon))
    end
  end
  alias autenticacao_usuario autenticar_usuario

  def autorizar_usuario
    unless session[:usuario].nome
      session[:uri]  = request.request_uri
      flash[:notice] = "Sessão expirada. Não necessário iniciar a sessão."
      self.autenticar
    end if session[:usuario]

  end
  alias autorizacao_usuario autorizar_usuario

  def autenticar
    redirect_to url_for(:controller => '/autenticacao', :action => :logon)
  end

  def limpar_mensagens
    flash[:notice]  = nil
    flash[:message] = nil
    flash[:warning] = nil
    flash.discard
  end
end